package com.yuma.springaialibaba.controller;

import com.alibaba.cloud.ai.dashscope.audio.DashScopeSpeechSynthesisModel;
import com.alibaba.cloud.ai.dashscope.audio.DashScopeSpeechSynthesisOptions;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisPrompt;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

@RestController
public class AISpeechSynthesisModelController {
    @Autowired
    private DashScopeSpeechSynthesisModel speechSynthesisModel;

    @GetMapping("/ali/speech/{msg}")
    public void tts(@PathVariable String msg) throws IOException {

        DashScopeSpeechSynthesisOptions options = DashScopeSpeechSynthesisOptions.builder()
                .speed(1.0f) // 语速
                .pitch(1.0)  // 音调
                .volume(50)   // 音量
                .model("sambert-zhichu-v1")
                .voice("zhichu-v1")
                .build();

        SpeechSynthesisResponse response = speechSynthesisModel.call(
                new SpeechSynthesisPrompt(msg, options));
        File file = new File("E:\\0324\\workspace\\ai-parent\\spring-ai-alibaba\\src\\main\\resources\\output.mp3");
        if (!file.exists()){
            file.createNewFile();
        }
        try (FileOutputStream fos = new FileOutputStream(file)) {
            ByteBuffer byteBuffer = response.getResult().getOutput().getAudio();
            fos.write(byteBuffer.array());
            fos.flush();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
